package com.zd.certificate.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DynamicDataSource extends AbstractRoutingDataSource  {
    static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);

    private final Map<Object, Object> dsMap = new ConcurrentHashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = DataSourceContextHolder.get();
        System.err.println("determineCurrentLookupKey() ->"+ dataSource);
        if(dataSource == null){
            logger.info("当前数据源为[primary]");
        }else{
            logger.info("当前数据源为{}",dataSource);
        }
        return dataSource;
    }

    public void setDataSource(int userId, DataSource dataSource){
        String dsKey = getDataSourceKey(userId);
        if(dsMap.get(dsKey) == null){
            //缓存-下次再创建时,判断缓存是否存在,避免多次创建
            dsMap.put(dsKey,dataSource);
            super.setTargetDataSources(dsMap);
            super.afterPropertiesSet();
        }
        DataSourceContextHolder.set(dsKey);
    }
    public DataSource getDataSource(String dsKey){
        return (DataSource)dsMap.get(dsKey);
    }

    public static String getDataSourceKey(int userId){
        if(userId == 0){
            return MultipleDataSourceConfig.PRIMARY_DS;
        }
        return "datasource-"+userId;
    }


}
